package cn.hloger.spider.demo.webSocketDemo.server.impl;

import cn.hloger.spider.demo.webSocketDemo.handle.WsMessageHandle;
import cn.hloger.spider.demo.webSocketDemo.server.BaseWebsocketServer;
import cn.hloger.spider.demo.webSocketDemo.service.ChatRoomHandle;
import cn.hloger.spider.demo.webSocketDemo.service.SessionHandle;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * socket的客户端
 * onOpen: 当客户端建立 WebSocket 连接时触发。
 * onMessage: 当接收到客户端发送的消息时触发。
 * onClose: 当客户端关闭 WebSocket 连接时触发。
 * onError: 当出现错误时触发。
 *
 * @author huanglong
 * @version 1.0
 * @date 2024/2/27
 */
@Component
@Slf4j
@ServerEndpoint("/chat/{taskId}")
public class ChatRoomImpl extends BaseWebsocketServer {


    static final Pattern pattern = Pattern.compile("@(\\w+)\\s(.*)");

    static final String PRIVATE_CHAT = "%s悄悄的对你说:%s";

    static final String PUBLIC_CHAT = "%s说:%s";

    static final String ADMIN = "admin";

    /**
     * 聊天室的话, 就需要把接收到的消息发给全体, 除了他自己
     *
     * @param message
     */
    @OnMessage
    public void onMessage(String message, Session session) throws IOException {
        log.info("收到消息: " + message);
        String localName = SessionHandle.getNameBySession(session);
        Matcher matcher = pattern.matcher(message);
        if (matcher.find()) {
            privateChat(message, session, localName, matcher);
        } else {
            //全局回复
            sendAllWithOutSession(String.format(PUBLIC_CHAT, localName, message), session);
        }

    }

    private void privateChat(String message, Session session, String localName, Matcher matcher) {
        //私聊
        String targetUser = matcher.group(1);
        if (targetUser.equals(ADMIN)) {
            //管理员命令
            sendMessage(ChatRoomHandle.handleAdminOrder(matcher.group(2), sessionPools), session);
        } else {
            //需要私聊
            Session targetsession = SessionHandle.getSessionByName(targetUser, sessionPools);
            if (session != null) {
                sendMessage(String.format(PRIVATE_CHAT, localName, message), targetsession);
            } else {
                //给自己消息
                sendMessage("未找到用户:" + targetUser, session);
            }
        }
    }


    /**
     * 连接成功
     *
     * @param session
     */
    @OnOpen
    public void onOpen(Session session,
                       @PathParam(value = "taskId") String taskId) {
        String localName = SessionHandle.getNameBySession(session);
        //1.链接成功,把session放入map中,之后使用的时候方便发送
        sessionPools.put(taskId, session);
        //2. 给session加钟
        session.setMaxIdleTimeout(MAX_TIME_OUT);
        log.info("{}加入webSocket！当前人数为{}", localName, onlineNum.incrementAndGet());
        // 查询当前id是否存在队列,如果不在,那么就可以走了
        WsMessageHandle handle = messageHandlePool.get(taskId);
        if (Objects.nonNull(handle)) {
            handle.sendMsg(session, executorService);
            sendAllMessage(String.format("恭喜尊贵的会员%s回到聊天室,当前聊天室人数:%s,", localName, onlineNum));
        } else {
            sendAllMessage(String.format("恭喜尊贵的会员%s加入聊天室,当前聊天室人数:%s,", localName, onlineNum));
        }
    }

}
